package sw6.launcher;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class IconAdapter extends BaseAdapter {
	private Context mContext;
	protected final String tag = "GIRAF";
	protected List<ResolveInfo> applications;
	protected List<Drawable> icons;
	
	/**
	 * Constructs the IconAdapter within the given context
	 * @param c The context in which the adapter is used.
	 */
    public IconAdapter(Context c) {
        mContext = c;
        applications = buildInfos();
        icons = buildIcons();
    }
    
    /** Gets the number of installed GIRAF applications */
	@Override
	public int getCount() {
		return applications.size();
	}
	
	/** Gets the ResolveInfo object at the given position. */
	@Override
	public Object getItem(int position) {
		return applications.get(position);
	}

	/** Not Used */
	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	/** Gets the ImageView for the given position. */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageDrawable(icons.get(position));
        return imageView;
	}

	/**
	 * Gets the list of applications with the "sw6.intent.action.MAIN" 
	 * intent from the packagemanager. It is only used internally by this adapter.
	 * NOTE: THIS VERSION USES "android.intent.action.MAIN"!!
	 * @return A list of ResolveInfos containing the applications to be launched.
	 */
	private List<ResolveInfo> buildInfos() {
		PackageManager pm = mContext.getPackageManager();

		Log.d(tag,"Getting a list of applications");
		Intent intent = new Intent("android.intent.action.MAIN");
		intent.addCategory("android.intent.category.LAUNCHER");
		
		List<ResolveInfo> result = pm.queryIntentActivities(intent,0); 
		
		return result;
	}
	
	/** Loads all icons from the ResolveInfo's in the applications list. */
	private List<Drawable> buildIcons() {
		List<Drawable> result = new ArrayList<Drawable>();
		
		for(ResolveInfo info: this.applications) {
			result.add(info.loadIcon(mContext.getPackageManager()));
		}
		
		return result;
	}
}
	